<template>
  <div class="pageOut">
    <div class="pageIn">
      <el-form :inline="true" :model="formSearch" size="small">
        <el-form-item>
          <el-input
            v-model="formSearch.merchant_name"
            placeholder="搜索商户名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formSearch.merchant_phone"
            placeholder="搜索商户手机"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formSearch.cityName"
            placeholder="搜索城市"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button icon="el-icon-search" @click="search">查询</el-button>
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="handleAdd"
            v-show="permission.add"
            >新增</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        border
        ref="table"
        :height="height - 170"
        :data="tableData"
        :header-cell-style="{ background: '#FAFAFA', color: '#606266' }"
        v-loading="loading"
        element-loading-background="rgba(255, 255, 255, 0.5)"
        style="width: 100%"
      >
        <el-table-column
          prop="merchantName"
          :show-overflow-tooltip="tooltip"
          label="商户名"
        ></el-table-column>

        <el-table-column
          prop="city"
          :show-overflow-tooltip="tooltip"
          label="商户地点"
        ></el-table-column>
        <el-table-column
          prop="userName"
          :show-overflow-tooltip="tooltip"
          label="联系人"
        ></el-table-column>
        <el-table-column
          prop="phone"
          :show-overflow-tooltip="tooltip"
          label="联系方式"
        >
        </el-table-column>
        <el-table-column
          prop="account"
          :show-overflow-tooltip="tooltip"
          label="收款账号"
        ></el-table-column>
        <el-table-column :show-overflow-tooltip="tooltip" label="设备管理">
          <template slot-scope="scope">
            <el-link type="primary" @click="examineClick(scope.row, '2')"
              >点击查看</el-link
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="create_time"
          :show-overflow-tooltip="tooltip"
          label="添加时间 "
        >
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="260" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleEdit(scope.row)"
              v-show="permission.edit"
              >修改</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="handleDel(scope.row.id)"
              v-show="permission.del"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>

      <el-dialog
        :title="editId == '' ? '新增' : '修改'"
        :visible.sync="visible"
        width="40%"
        @close="onCancel('ruleFormRef')"
      >
        <el-form
          label-width="100px"
          :model="ruleForm"
          ref="ruleFormRef"
          :rules="rules"
          style="margin: 30px 0px 10px 0px"
        >
          <div class="addEquioBox">
            <el-form-item label="商户名称" prop="merchant_name">
              <el-input
                style="width: 250px"
                v-model="ruleForm.merchant_name"
                placeholder="请输入商户名称"
              ></el-input>
            </el-form-item>
          </div>
          <div class="addEquioBox">
            <el-form-item label="联系人" prop="userName">
              <el-input
                style="width: 250px"
                v-model="ruleForm.userName"
                placeholder="请输入联系人"
              ></el-input>
            </el-form-item>
            <el-form-item label="联系方式" prop="merchant_phone">
              <el-input
                oninput="this.value=this.value.replace(/[^\d]/g,'')"
                v-model="ruleForm.merchant_phone"
                style="width: 250px"
                placeholder="请输入联系方式"
              ></el-input>
            </el-form-item>
          </div>
          <el-form-item label="收款账号类型">
            <el-radio v-model="ruleForm.accountType" label="1">对公</el-radio>
            <el-radio v-model="ruleForm.accountType" label="2">对私</el-radio>
          </el-form-item>
          <div class="addEquioBox">
            <el-form-item label="开户行" prop="merchant_image">
              <el-input
                v-model="ruleForm.merchant_image"
                style="width: 250px"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item label="收款账号" prop="merchant_address">
              <el-input
                oninput="this.value=this.value.replace(/[^\d]/g,'')"
                v-model="ruleForm.merchant_address"
                style="width: 250px"
                placeholder="请输入收款账号"
              ></el-input>
            </el-form-item>
          </div>
          <el-form-item label="结款周期">
            <el-radio v-model="ruleForm.settlementPeriod" label="1"
              >周</el-radio
            >
            <el-radio v-model="ruleForm.settlementPeriod" label="2"
              >月</el-radio
            >
            <el-radio v-model="ruleForm.settlementPeriod" label="3"
              >年</el-radio
            >
          </el-form-item>
          <el-form-item label="合同到期日期" prop="time" label-width="120px">
            <el-date-picker
              v-model="ruleForm.time"
              :picker-options="pickerOptions"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label-width="120px">
            <el-button type="primary" @click="location">打开地图</el-button>
          </el-form-item>

          <el-form-item v-if="ruleForm.address" label="详细地址" prop="address">
            <el-input disabled v-model="ruleForm.address"> </el-input>
          </el-form-item>
        </el-form>
        <div class="btnBox">
          <el-button type="primary" @click="addClick('ruleFormRef')"
            >确 定</el-button
          >
        </div>
      </el-dialog>

      <!-- 地图弹框 -->
      <el-dialog
        top="6vh"
        :show-close="false"
        :visible.sync="MapVisible"
        width="600px"
      >
        <!-- style="width:400px;height:400px" -->
        <div>
          <SelectMap
            v-if="MapVisible"
            @getMapInfo="getMapInfo"
            :center="ruleForm.center"
            style="height: 600px"
          />
        </div>
        <div slot="footer">
          <el-button @click="MapVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleMap">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  commercialList,
  merchantDel,
  agentPull,
  merchantEdit,
  merchantAdd,
  MAIN,
} from "../../utils/api";
import test from "./test";
import SelectMap from "../../components/SelectMap";

import UploadImg from "../../components/UploadImage";

export default {
  components: {
    test,
    UploadImg,
    SelectMap,
  },
  name: "MemberControl",
  props: ["height"],

  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; //禁用今日之前的日期
          // return time.getTime() > Date.now(); //禁用今日之后的日期
        },
        // disabledDate: (time) => time.getTime() > new Date() * 1 + 600 * 1000,
      },
      MapVisible: false,
      tableData: [],
      goodsDialog: false,
      editId: "",
      tooltip: true, //内容过长被隐藏时显示 tooltip
      loading: true, //显示加载表格
      pageSize: 10, //每页多少条
      currentPage: 1, //当前第几页
      pageSizes: [10, 20, 30, 40, 50], //每页选择条数
      total: 0, //共多少条
      errImg: 'this.src="' + require("../../../static/img/user.png") + '"',
      formSearch: {
        merchant_name: "",
        merchant_phone: "",
        cityName: "",
        agentPhone: "",
      }, //搜索
      //编辑弹窗
      visible: false,
      permission: {
        add: false,
        banner: false,
        edit: false,
        del: false,
      }, //权限
      confirmLoading: false,
      type: "add",
      currentRow: {}, //当前行数据信息
      ruleForm: {
        address: "",
        userName: "",
        merchant_name: "",
        merchant_phone: "",
        merchant_member_name: "",
        merchant_image: "",
        merchant_content: "",
        merchant_address: "",
        accountType: "1",
        center: [116.397128, 39.916527],
        settlementPeriod: "1",
        time: "",
        lon: "",
        lat: "",
      }, //添加和修改的表单
      rules: {
        merchant_name: [
          { required: true, message: "请输入商户名称", trigger: "blur" },
        ],
        merchant_phone: [
          {
            required: true,
            message: "请输入联系方式",
            trigger: "blur",
          },
          // {
          //   validator: function (rule, value, callback) {
          //     if (/^1[34578]\d{9}$/.test(value) == false) {
          //       callback(new Error("请输入正确的手机号"));
          //     } else {
          //       callback();
          //     }
          //   },
          //   trigger: "blur",
          // },
        ],
        time: [{ required: true, message: "请选择日期", trigger: "blur" }],
        userName: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        merchant_address: [
          { required: true, message: "请输入收款账号", trigger: "blur" },
        ],
        merchant_image: [
          { required: true, message: "请输入开户行", trigger: "blur" },
        ],
      },
      MapVisible: false, //地图的弹出框
      ap: {}, //地图的经纬度
      userInfo: {},
    };
  },

  mounted() {
    this.getResource();
    if (this.$route.query.agentId) {
      this.agentId = this.$route.query.agentId;
      this.getData();
    }
  },
  methods: {
    //获取权限资源
    getResource() {
      // console.log(this.$route.name);
      this.loading = true;
      const userinfo = JSON.parse(sessionStorage.getItem("userInfo")); //解密,获取用户登录信息
      this.userInfo = userinfo;
      let arr = userinfo.menu_id.split(",");
      // console.log(arr)
      // 新增 105
      // 修改 106
      // 删除 107

      if (arr.indexOf("105") > -1) {
        this.permission.add = true;
      }
      if (arr.indexOf("106") > -1) {
        this.permission.edit = true;
      }

      if (arr.indexOf("107") > -1) {
        this.permission.del = true;
      }

      this.getData();
    },
    //获取初始数据
    getData() {
      this.loading = true;
      let params = {
        merchantName: this.formSearch.merchant_name,
        phone: this.formSearch.merchant_phone,
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
        cityName: this.formSearch.cityName,
        agentPhone: this.formSearch.agentPhone,
        agentId: this.agentId,
      };
      this.postRequest(commercialList, params, MAIN).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.count;
          this.loading = false;
          this.$nextTick(() => {
            //避免表格表头样式错乱
            if (this.$refs.table) this.$refs.table.doLayout();
          });
        }
      });
    },

    // 选择图片
    getImgSrc2(v) {
      this.ruleForm.merchant_image = v;
    },
    //分页
    handleSizeChange(val) {
      //每页 ${val} 条
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      //当前页
      this.currentPage = val;
      this.getData();
    },
    //查询
    search() {
      this.getData();
    },
    //新增
    handleAdd() {
      this.type = "add";
      this.currentRow = {};
      this.visible = true;
    },
    //编辑
    handleEdit(row) {
      this.editId = row.id;
      this.currentRow = row;
      this.visible = true;
      let obj = row.city;
      // 返回一个指定的字符串值最后出现的位置，在一个字符串中的指定位置从后向前搜索
      var index = obj.lastIndexOf("-");
      // 截取
      obj = obj.substring(index + 1, obj.length);
      this.ruleForm = {
        userName: row.userName,
        merchant_name: row.merchantName,
        merchant_phone: row.phone,
        merchant_member_name: "",
        merchant_image: row.bankName,
        merchant_content: "",
        merchant_address: row.account,
        accountType: String(row.accountType),
        center: [row.lon, row.lat],
        settlementPeriod: String(row.settlementPeriod),
        time: row.end_time,
        lon: "",
        lat: "",
        cityName: obj,
        address: row.address,
      };
    },
    // 点击查看
    examineClick(row, type) {
      switch (type) {
        case "1":
          break;
        case "2":
          this.$router.push({
            name: "LockerList",
            query: {
              merchantId: row.id,
            },
          });
          break;
        case "3":
          break;
        case "4":
          break;
      }
    },
    //删除
    handleDel(id) {
      let parm = {
        id: id,
        userId: this.userInfo.id,
      };
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.postRequest(merchantDel, parm, MAIN).then((res) => {
            // console.log(res);
            if (res.code == 200) {
              this.$notify({
                title: "成功",
                message: res.msg,
                type: "success",
              });
              this.getData();
            }
          });
        })
        .catch(() => {});
    },

    addClick(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          let params = {
            merchantName: this.ruleForm.merchant_name,
            account: this.ruleForm.merchant_address,
            bankName: this.ruleForm.merchant_image,
            address: this.ruleForm.address,
            userName: this.ruleForm.userName,
            phone: this.ruleForm.merchant_phone,
            accountType: this.ruleForm.accountType,
            settlementPeriod: this.ruleForm.settlementPeriod,
            end_time: this.ruleForm.time,
            lon: this.ruleForm.center[0],
            lat: this.ruleForm.center[1],
            userId: this.userInfo.id,
            cityName: this.ruleForm.cityName,
          };
          if (this.editId == "") {
            this.postRequest(merchantAdd, params, MAIN).then((res) => {
              if (res.code === 200) {
                this.$notify.success(res.msg);
                this.getData();
                this.visible = false;
              }
              this.confirmLoading = false;
            });
          } else {
            params.id = this.editId;
            this.postRequest(merchantEdit, params, MAIN).then((res) => {
              if (res.code === 200) {
                this.visible = false;

                this.$notify.success(res.msg);
                this.getData();
              }
              this.confirmLoading = false;
            });
          }
        } else {
          return false;
        }
      });
    },
    onCancel(formName) {
      this.$refs[formName].resetFields();
      this.onReset();
    },
    //清空重置表单
    onReset() {
      this.visible = false;
      this.editId = "";
      this.confirmLoading = false;
      this.ruleForm = {
        userName: "",
        address: "",
        merchant_name: "",
        merchant_phone: "",
        merchant_member_name: "",
        merchant_image: "",
        merchant_content: "",
        merchant_address: "",
        accountType: "1",
        center: [116.397128, 39.916527],
        settlementPeriod: "1",
        time: "",
        lon: "",
        lat: "",
        cityName: "",
      };
    },
    goBannerList(row) {},
    // 选择经纬度
    handleMap() {
      this.MapVisible = false;
    },
    //定位
    location() {
      this.MapVisible = true;
    },
    //获取位置内容
    getMapInfo(val) {
      console.log(val);
      const pname = val.pname && val.pname !== null ? val.pname : ""; //省
      const cityname =
        val.cityname && val.cityname !== null ? val.cityname : ""; //市
      const adname = val.adname && val.adname !== null ? val.adname : ""; //区
      const address = val.address && val.address !== null ? val.address : ""; //详细地址
      const tel =
        val.tel && val.tel !== null
          ? Array.isArray(val.tel)
            ? val.tel.join(",")
            : val.tel
          : ""; //服务电话
      this.ruleForm.address = `${pname}${cityname}${adname}${address}`;
      this.ruleForm.cityName = cityname;
      this.ruleForm.center =
        val.location && val.location !== null
          ? val.location.split(",")
          : [116.397128, 39.916527]; //经纬度
      // this.ruleForm.center = val.location.split(",");
    },
  },
};
</script>

<style scoped>
/deep/ .el-input-group__append,
.el-input-group__prepend {
  background-color: #1890ff;
  color: #fff;
  cursor: pointer;
}
/deep/ .el-input--mini .el-input__inner {
  height: 32px;
  line-height: 32px;
}
.addEquioBox {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-left: 20px;
}
.btnBox {
  margin-top: 20px;
  width: 100%;
  display: flex;
  justify-content: center;
}
</style>
